package com.Webserver.controller;

import com.Webserver.http.HttpRequest;
import com.Webserver.http.HttpResponse;
import com.Webserver.vo.User;

import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 用来处理和用户相关的业务操作
 */
public class UserController {
    //保存所有用户信息的目录的名字
    private static String userDirName = "./users/";

    static {
        //程序加载时判断一下保存所有用户信息的的目录是否存在，不存在先自动创建出来.
        File userDir = new File(userDirName);
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    /**
     * 用来处理用户注册操作
     *
     * @param request
     * @param response
     */
    public void reg(HttpRequest request, HttpResponse response) {
        System.out.println("开始处理用户注册...");
        /**1.从request中获取用户表单上提交的注册信息*/

        //注:request.getParameter()获取表单某输入框上的内容要传递的参数为该输入框name=""属性指定
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);
        /*
            必要的验证工作，保证注册的四个信息不为空，否则直接响应注册失败的提示页面.
            失败页面:reg_error.html 居中显示一行字:注册失败，输入信息有误，请重新注册.
         */
        if (username == null || password == null || nickname == null || ageStr == null || !ageStr.matches("[0-9]+")) {
            System.out.println("注册失败，输入信息有误，请重新输入...");
            response.setEntity(new File("./webapps/myweb/reg_error.html"));
            return;
        }
        /* 判断是否为重复用户，如果是重复用户则为直接响应页面:reg_have_user.html
         *   该页面居中显示一行字:该用户已存在，请重新注册.
         */
        File file = new File(userDirName + username + ".obj");
        if (file.exists()) {
            System.out.println("该用户已存在，请重新输入...");
            response.setEntity(new File("./webapps/myweb/reg_have_user.html"));
            return;
        }
        int age = Integer.parseInt(ageStr);
        /**2.将该用户信息写入磁盘保存*/
        User user = new User(username, password, nickname, age);
        try (
                ObjectOutputStream oos = new ObjectOutputStream(
                        new FileOutputStream(userDirName + username + ".obj")
                );
        ) {
            oos.writeObject(user);
            //注册成功,
            response.setEntity(new File("./webapps/myweb/reg_success.html"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        /**3.设施response响应注册结果页面*/
        System.out.println("用户注册处理完毕!!!");
    }

    public void login(HttpRequest request, HttpResponse response) {
        System.out.println("等待用户登录...");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用户名:" + username + "密码:" + password);

        if (username == null || password == null) {
            response.setEntity(new File("./webapps/myweb/login_error.html"));
            return;
        }

        File file = new File(userDirName + username + ".obj");
        if (file.exists()) {
            try (
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            ) {
                User user = (User) ois.readObject();
                String code = user.getPassword();
                System.out.println(user);
                if (password.equals(code)) {
                    response.setEntity(new File("./webapps/myweb/login_success.html"));
                    System.out.println("登录成功!!");
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        response.setEntity(new File("./webapps/myweb/login_fail.html"));
        System.out.println("登录处理完毕!!");
    }
    public void showAllUser(HttpRequest request,HttpResponse response) {
        System.out.println("页面生成中...");
        /*
            1:将Users目录下的所有.obj文件获取到，并逐个进行反序列化来得到若干个User对象。
            然后将这些User对象都存入一个List集合备用.
         */
        List<User> userList = new ArrayList<>();
        File userDir = new File(userDirName);
        if(userDir.isDirectory()){
//            FileFilter filter = new FileFilter() {
//                @Override
//                public boolean accept(File user) {
//                    return user.getName().endsWith(".obj");
//                }
//            };
//            File[] subs = userDir.listFiles(filter);
            File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));
            for(File userFile : subs){
                try(
                    FileInputStream fis = new FileInputStream(userFile);
                    ObjectInputStream ost = new ObjectInputStream(fis);
                    ) {
                    User str = (User) ost.readObject();
                    userList.add(str);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            userList.forEach(System.out::println);

            try {
                File htmlFile = new File("./userList.html");
                PrintWriter pw = new PrintWriter(htmlFile);
                pw.println("<!DOCTYPE html>");
                pw.println("<html lang=\"en\">");
                pw.println("<head>");
                pw.println("<meta charset=\"UTF-8\">");
                pw.println("<title>用户列表</title>");
                pw.println("</head>");
                pw.println("<body>");
                pw.println("<center>");
                pw.println("<h1>用户列表</h1>");
                pw.println("<table border=\"2\">");
                pw.println("<tr>");
                pw.println("<td>用户名</td>");
                pw.println("<td>密码</td>");
                pw.println("<td>昵称</td>");
                pw.println("<td>年龄</td>");
                pw.println("</tr>");
                for (User user : userList) {
                    pw.println("<tr>");
                    pw.println("<td>"+user.getUsername()+"</td>");
                    pw.println("<td>"+user.getPassword()+"</td>");
                    pw.println("<td>"+user.getNickname()+"</td>");
                    pw.println("<td>"+user.getAge()+"</td>");
                    pw.println("</tr>");
                }
                pw.println(" </table>");
                pw.println("</center>");
                pw.println("</body>");
                pw.println("</html>");

                pw.flush();
                response.setEntity(htmlFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
        System.out.println("页面生成完毕!!");
    }
}
